package org.nobody.mallb2c.mallmember.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 3489309323@qq.com
 * @create 2020-09-21-22:23
 */
@Configuration
public class FeignConfig {
  @Bean("requestInterceptor")
  public RequestInterceptor requestInterceptor(){
    return new RequestInterceptor() {
      @Override
      public void apply(RequestTemplate template) {
        System.out.println("requestInterceptor 线程id:"+Thread.currentThread().getId());

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); //就是用的thread local
        System.out.println("requestInterceptor requestAttributes: "+ requestAttributes);
        if(requestAttributes == null) return;
        HttpServletRequest request = requestAttributes.getRequest(); //老请求
        if (request != null) {
          //同步请求头数据 Cookie
          String cookie = request.getHeader("Cookie");
          //给新请求同步了老请求的cookie
          template.header("Cookie", cookie);
        }
      }
    };
  }
}
